using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.Mvc;
using viBook.Filters;
using viBook.Helpers;
using viBook.ModelBinders;
using viBook.Models;

namespace viBook.Controllers
{
    public class ChaptersController : BaseController
    {
        #region Constructors and Repository vars

        private readonly IBookRepository _bookRepository = new BookRepository();
        private readonly IChapterRepository _chapterRepository;

        public ChaptersController()
            : this(new ChapterRepository())
        {
        }

        public ChaptersController(IChapterRepository chapterRepository)
        {
            _chapterRepository = chapterRepository;
        }

        #endregion

        public ViewResult Details(int id)
        {
            var chapter = _chapterRepository.Find(id);
            return View(chapter);
        }


        public ActionResult Create(int bookid)
        {
            if (bookid != 0)
            {
                var chapter = new Chapter {BookId = bookid};
                return View(chapter);
            }

            return View();
        }

        [HttpPost]
        public ActionResult Create(Chapter chapter)
        {
            if (ModelState.IsValid)
            {
                 chapter.Pages = new List<Page>();
                var images = Request["fileUploadInfo"];
                string[] listImage = images.Split(new[] {';'}, StringSplitOptions.RemoveEmptyEntries);

                foreach (var image in listImage)
                {
                    if (!string.IsNullOrEmpty(image))
                    {
                        var imagepath = image.Replace(Server.MapPath("~"), "/").Replace("\\","/");
                        //add the first image of list image become chapterimg
                        if (string.IsNullOrEmpty(chapter.ChapterImage))
                            chapter.ChapterImage = imagepath;

                        chapter.Pages.Add(new Page
                                              {
                                                  ImageSource = imagepath
                                              });
                    }
                }
                chapter.NumberOfPages = chapter.Pages.Count;
                _chapterRepository.InsertOrUpdate(chapter);
                //_chapterRepository.Save();-saved at respository
                
                return RedirectToAction("Details", "Books", new {id = chapter.BookId});
            }
            else
            {
                return View();
            }
            return View();
        }

        public ActionResult Edit(int id)
        {
            return View(_chapterRepository.Find(id));
        }


        [HttpPost]
        public ActionResult Edit(Chapter chapter)
        {
            if (ModelState.IsValid)
            {
                _chapterRepository.InsertOrUpdate(chapter);
                _chapterRepository.Save();
                return RedirectToAction("Details");
            }
            else
            {
                return View();
            }
        }

        [HttpPost, ActionName("Delete"), Authorize]
        public ActionResult DeleteConfirmed(int id)
        {
            _chapterRepository.Delete(id);
            _chapterRepository.Save();

            return RedirectToAction("Index", "Account");
        }

        public string UploadFiles(HttpPostedFileBase FileData, FormCollection forms)
        {
            try
            {
                var savedFilename = string.Empty;
                var folder = string.Empty;
                if (!string.IsNullOrEmpty(forms.Get("path")))
                {
                    folder = forms.Get("path");
                }


                foreach (string file in Request.Files)
                {
                    HttpPostedFileBase postedFileBase = Request.Files[file];

                    if (postedFileBase != null && postedFileBase.ContentLength > 0)
                    {
                        var filename = DateTime.Now.ToString("dd-MM-yyyy") + "_" + DateTime.Now.Second.ToString("00") + Path.GetFileName(postedFileBase.FileName);


                        savedFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, folder, filename);
                        if (!Directory.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, folder)))
                            Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, folder))
                            ;

                        postedFileBase.SaveAs(savedFilename);
                    }
                }

                return savedFilename;


            }
            catch (Exception e)
            {
                return (e.Message);
            }
        }
            

        [HttpPost, Authorize]
        public JsonResult Like(int chapterId)
        {
            _chapterRepository.Like(chapterId, ExtendedIdentity.Id);
            return _successFeedback;
        }

        [HttpPost]
        public ActionResult Report(int chapterId)
        {
            _chapterRepository.Report(chapterId, ExtendedIdentity.Id);
            return _successFeedback;
        }
    }
}
